How to Automatically Add User Info to Logs

Log::withContext adds a global context to all logs within the current request.


Log::withContext in Laravel allows you to add extra information (like user details or other relevant data) to every log entry automatically, without having to repeat it in each log message.

For example, if you want to track which user is triggering actions in your application, you can use Log::withContext to include the user’s ID in all logs for better debugging and tracking.

Log User info without Log::withContext

\Log::info('User has logged in.', ['id' => auth()->id()]);

// output: local.INFO: User has logged in. {"id":1} 

Log User info with Log::withContext

// in handle function of a middleware
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class MyMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): 
     * (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        Log::withContext([
            'user-id' => auth()->id()
        ]);

        return $next($request);
    }
}

then in controller or anywhere you want to create a log

Route::get('/log', function () {
    \Log::info('User performed an action');
})->middleware('my.middleware');

// output: local.INFO: User performed an action {"user-id":1} 

Log::withContext: Adds a global context (e.g., user_id) to all logs within the current request. This means every log entry made afterward will automatically include the user_id in the context.

auth()->id(): Retrieves the currently authenticated user’s ID.

You Might Also Like

Route Resource Controllers for CRUD Operations

Resource controllers simplifies CRUD operations and keeps codebase organized and maintainable by fol...

Use Lazy Eager Loading for Conditional Relationships

Load related models only when needed using lazy eager loading. This technique helps in optimizing qu...